package admin.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import models.CategoryModel;
import models.LinkModel;

import admin.data.CategoryData;
import admin.data.LinkData;
import admin.forms.LinkForm;

public class AddLinkServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		TreeMap check = new TreeMap();
		CategoryData cData = new CategoryData();
		ArrayList<CategoryModel> categories = cData.listAll();
		LinkModel link = new LinkModel();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/admin/pages/form_link.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		CategoryData cData = new CategoryData();
		LinkForm linkForm = new LinkForm();
		LinkData linkData = new LinkData();
		LinkModel link = new LinkModel();
		request.setAttribute("permission", "admin");
		//Check value valid form
		TreeMap forms = (TreeMap) linkForm.checkValid(request, link); 
		link = (LinkModel) forms.get("link");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (link.getType().equalsIgnoreCase("reciprocal")) {
			if (check.get("urlReciprocal") == null) {
				link.setStatus(2);
			}
		}
		
		if(check.size() == 0)
	    {
			linkData.insert(link);
			request.setAttribute("success", "Add success link " + link.getId());
			link = new LinkModel();
	    }
		
		ArrayList<CategoryModel> categories = cData.listAll();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("categories", categories);
		request.setAttribute("link", link);
		try {
			request.getRequestDispatcher("/admin/pages/form_link.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	private boolean checkLinkReciprocal(String urlReciprocal, String sourceReciprocal) {
		boolean isContain = false;
		try {
			String content = Jsoup.connect(urlReciprocal).get().html();
			if (content.contains(sourceReciprocal)) {
				isContain = true;
			}
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return isContain;
	}
}
